import { getUserInfo, login } from '@/global/api/user'
import { getToken, removeToken, setToken } from '@/global/utils/auth'
import { resetRouter } from '@/router'
import { defineStore } from 'pinia'


export const useUserStore = defineStore('user', {
  state: () => {
    return {
      userInfo: null as null | KeyValue,
      token: getToken()
    }
  },

  getters: {
    getUserInfoGetter: (state) => state.userInfo
  },

  actions: {
    // 登录
    login(loginInfo: KeyValue) {
      const { username, password } = loginInfo
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password }).then((res: KeyValue) => {
          if (Number(res.code) === 200) {
            this.$patch(state => {
              state.token = res.data ? res.data : ''
            })
            setToken(res.data ? res.data : '')
            resolve(true)
          } else reject()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    getUserInfo() {
      return new Promise(resolve => {
        getUserInfo().then(res => {
          this.$patch(state => state.userInfo = res.data)
          resolve(true)
        })
      })
    },
    // 登出
    logout() {
      return new Promise((resolve, reject) => {
        removeToken() // must remove  token  first
        resetRouter()
        this.$patch(state => {
          state.userInfo = null
          state.token = ''
        })
        resolve(true)
      })
    }
  }
})
